package top.yonyong.mynacos.configcenter.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yonyong.mynacos.configcenter.dao.ConfigRepository;
import top.yonyong.mynacos.configcenter.pojo.ConfigBean;
import top.yonyong.mynacos.configcenter.pojo.ConfigInfo;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @Describtion Todo
 * @Author yonyong
 * @Date 2020/7/6 10:33
 * @Version 1.0.0
 **/
@RestController
@RequestMapping("/v1/cs/")
public class ConfigController {
    @Resource
    private ConfigRepository configRepository;

    @RequestMapping("configs")
    public Object configs(@Valid final ConfigBean cb) {
        if (StringUtils.isBlank(cb.getContent()))
            return handleGet(cb);
        else
            return handlePut(cb);
    }

    private Object handleGet(@Valid ConfigBean cb) {
        final List<ConfigInfo> infoList = configRepository.queryAllByKeyAndGroupOrderByUpdateTime(cb.getDataId(),cb.getGroup());
        return infoList;
    }

    private Object handlePut(@Valid ConfigBean cb) {
        ConfigInfo ci = ConfigInfo.builder()
                .key(cb.getDataId())
                .val(cb.getContent())
                .group(cb.getGroup())
                .createTime(new Date())
                .handler("YONYONG")
                .build();
        final ConfigInfo save = configRepository.save(ci);
        return save;
    }
}
